package com.hk.web.controller.api.backend;

import com.hk.commons.JsonResult;
import com.hk.commons.ProcessAPI;
import com.hk.commons.utils.CglibBeanUtils;
import com.hk.web.controller.Routes;
import com.hk.web.domain.entity.OperationLog;
import com.hk.web.domain.entity.User;
import com.hk.web.domain.lifeCycle.repository.OperationLogRepository;
import com.hk.web.domain.lifeCycle.repository.UserRepository;
import com.hk.web.dto.operation.OperationLogDTO;
import com.hk.commons.constant.ReplaceTemplate;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 *
 * @author Antinomy
 * @date 17/12/11
 */
@RestController
@Api(value = "后台系统操作日志", description = "后台系统操作日志")
public class OperationLogBackendAPIController {



    @Autowired
    private OperationLogRepository operationLogRepo;

    @Autowired
    private UserRepository userRepo;


    @ApiOperation(value = "记录日志", notes = "记录日志", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiImplicitParam(name = "dto", value = "权限菜单基本信息", required = true, dataType = "OperationLogDTO")
    @RequestMapping(value = Routes.API_BACKEND_OPERATION_LOGGING, method = RequestMethod.POST)
    @ResponseBody
    public JsonResult store(HttpServletRequest request, @RequestBody OperationLogDTO dto) {

        ProcessAPI api = (jsonResult, validate) -> {
            validate.check("operatorId", dto.getOperatorId());

            OperationLog result = new OperationLog();
            CglibBeanUtils.copy(result,dto);

            User user = userRepo.findByUserId(dto.getOperatorId().toString());
            if(user != null){
                result.setOperatorMobile(user.getName());
                result.setOperatorName(user.getRealName());

                String eventDesc = getEventDesc(dto, user);
                result.setEventDesc(eventDesc);
            }

            result = operationLogRepo.saveAndFlush(result);

            jsonResult.result = result;
            jsonResult.size = 1L;
        };

        return api.process(request);

    }

    public String getEventDesc(@RequestBody OperationLogDTO dto, User user) {
        String descTemplate = dto.getEvent().getDescTemplate();

        String result = descTemplate.replaceAll(ReplaceTemplate.OPERATOR_NAME, user.getRealName());

        if(StringUtils.isNoneBlank(dto.getOperateItemName())){
             result = result.replaceAll(ReplaceTemplate.OPERATE_ITEM_NAME, dto.getOperateItemName());
        }

        if(StringUtils.isNoneBlank(dto.getOperateItemId())){
            result = result.replaceAll(ReplaceTemplate.OPERATE_ITEM_ID, dto.getOperateItemId());
        }

        return result;
    }

}
